//
// Created by wujehy on 2020/5/29.
//

#include "KeyValueBase.h"

using namespace GeeJoan::DataBase;

KeyValueDataTypePort KeyValueBase::Get(std::string &key)
{
    auto find = cacheKeyValueMap.find( key );
    if (find == cacheKeyValueMap.end())
    {
        return nullptr;
    } else
    {
        return find->second;
    }
}

KeyValueBase::~KeyValueBase()
{

    for (auto v : cacheKeyValueMap)
    {
        v.second.reset();
    }
    cacheKeyValueMap.clear();

}

KeyValueDataTypePort KeyValueBase::Get2(std::string key)
{
    return Get( key );

}

void KeyValueBase::setUserKey(std::string key, void *port, UserPortDeleteFunction deleteFunction)
{
    auto find = cacheKeyValueMap.find( key );
    // 已存在 删除 旧的 插入新的
    if (find != cacheKeyValueMap.end())
    {
        cacheKeyValueMap.erase( find );
    }
    cacheKeyValueMap[key] = std::shared_ptr<KeyValueDataType>( new KeyValueDataType( port, deleteFunction ));
}

void KeyValueBase::ForEcho(ForEchoCallbackFunction callbackFunction)
{
    for (auto v : cacheKeyValueMap)
    {
        callbackFunction( v.first, v.second );
    }
}
